<?php

namespace common\models;

use common\helpers\Image;
use common\Service\RedisService;
use Yii;
use common\models\Common;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%news}}".
 *
 * @property string $id
 * @property string $title
 * @property string $content
 * @property string $images
 * @property string $create_time
 * @property integer $in_redis
 * @property string $view
 */
class News extends Common
{
    public static $fields = ['title','content','id','image','view','create_time'];
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%news}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content', 'images'], 'string'],
            [['create_time', 'in_redis', 'view'], 'integer'],
            [['title'], 'string', 'max' => 200],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'images' => '图片',
            'create_time' => '创建时间',
            'in_redis' => 'In Redis',
            'view' => '浏览量',
        ];
    }

    /**
     * @desc ID倒序分页获取新闻列表数据
     * @param int $currentPage
     * @param int $perPage
     * @param array $fields
     * @return mixed
     */
    public static function pageNews($currentPage = 1,$perPage = 10,$fields = []){
        $rs = RedisService::pageData('newsZset',$currentPage,$perPage,'zset','desc');

        $rs['data'] = static::formatNews($rs['data'],$fields);

        return $rs;
    }

    public static function getNewsInfoById($newId = 0,$fields = []){
        $newId = intval($newId);
        if($newId < 1) return [];

        empty($fields) && $fields = static::$fields;

        $newInfo  = RedisService::getHash("news:".$newId,$fields);
        if(empty($newInfo)){
            $_newInfo = News::findOne($newId);
            if($_newInfo){
                RedisService::setHash("news:".$newId,$_newInfo->attributes);
                $newInfo = ArrayHelper::filter($_newInfo->attributes,$fields);
            }
        }

        $newInfo && $newInfo = static::formatNewInfo($newInfo);
        return $newInfo;
    }

    public static function incrementView($newId,$increment = 1){
        $newId = intval($newId);
        if($newId > 0 && Yii::$app->get('redis')->exists('news:'.$newId)){
                Yii::$app->get('redis')->hincrby('news:'.$newId,'view',1);
        }

    }

    /**
     * @desc 批量格式化新闻数据
     * @param array $newIDs
     * @param array $fields
     * @return array
     */
    public static function formatNews($newIDs = [],$fields = []){
        $rs = [];

        if($newIDs){
            empty($fields) && $fields = static::$fields;
            foreach ($newIDs as $id){
                $formatNewInfo = static::getNewsInfoById($id,$fields);
                if($formatNewInfo) $rs[] = $formatNewInfo;
            }
        }

        return $rs;
    }

    /**
     * @desc 格式化新闻数据
     * @param array $newInfo
     * @return array
     */
    public static function formatNewInfo($newInfo = []){
        //暂且使用替换域名的方法显示图片
        isset($newInfo['image']) && $newInfo['image'] = str_replace('http://img.guotuw.com',Yii::getAlias('@imgDomain'),$newInfo['image']);
        isset($newInfo['content']) && $newInfo['content'] = str_replace('http://img.guotuw.com',Yii::getAlias('@imgDomain'),$newInfo['content']);
        $newInfo['desc'] = isset($newInfo['content']) ? mb_substr(htmlspecialchars(strip_tags($newInfo['content'])),0,100) : '';
        return $newInfo;
    }

    /**
     * @desc 设置精华文章
     * @param int $id
     */
    public static function setFine($id = 0){
        if($id > 0) Yii::$app->redis->ZAdd('newsFineSSet',time(),$id);
    }

    public static function getFine($currentPage = 1,$perPage = 10,$fields = []){
        $rs = RedisService::pageData('newsFineSSet',$currentPage,$perPage,'zset','desc');

        $rs['data'] = static::formatNews($rs['data'],$fields);

        return $rs;
    }

    /**
     * @desc 删除精华文章
     * @param int $id
     */
    public static function delFine($id = 0){
        if($id > 0) Yii::$app->redis->ZRem('newsFineSSet',$id);
    }

    /**
     * @desc 基本新闻数据放入redis
     * @param int $id
     * @param array $newInfo
     * @return bool
     */
    public function setInfoToRedis($id = 0 , $newInfo = []){

        $id = intval($id);
        if($id == 0) return false;

        if(empty($newInfo) && $model = News::findOne($id)){
            $newInfo = array_merge($model->attributes,$newInfo);
        }

        $newInfo['images'] = json_decode($newInfo['images'],true);

        if(count($newInfo['images']) == 1){
            $newInfo['image'] = $newInfo['images'][0]['img'];
        }else{
            $scale = 0;
            foreach ($newInfo['images'] as $i=>$image){
                if($image['width'] == 0 || $image['height'] == 0){
                    $imgInfo = getimagesize(Yii::getAlias("@storage").'/'.explode('com/',$image['img'])[1]);
                    $image['width'] = $imgInfo[0];
                    $image['height'] = $imgInfo[1];
                    unset($imgInfo);
                }
                $_scale = round ($image['width'] / $image['height'],4);
                if($_scale > $scale && $image['height'] > 160){
                    $scale = $_scale;
                    $newInfo['image'] = $newInfo['images'][$i]['img'];
                }
            }
        }
        empty($newInfo['image']) && !empty($newInfo['images']) && $newInfo['image'] = $newInfo['images'][0]['img'];

        $imageAddress = Yii::getAlias("@storage").'/'.explode('com/',$newInfo['image'])[1];
        //生成新闻封面的缩略图
        $imageSize = filesize($imageAddress);
        $extension = pathinfo($imageAddress, PATHINFO_EXTENSION);
        if($imageSize > 100 * 1024){
            $imageName = basename($imageAddress);
            $coverName = str_replace($imageName,'cover.'.$extension,$imageAddress);
            $createSuccess = Image::mkThumbnail($imageAddress,234 * 2,null,$coverName);
            if($createSuccess){
                $newInfo['image'] = str_replace($imageName,'cover.'.$extension,$newInfo['image']);
            }
        }

        $newInfo['content'] = str_replace('|||','',$newInfo['content']);  //关掉抓取中的|||分页
        $newInfo['desc'] = htmlspecialchars($string = preg_replace ( "/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", '', $newInfo['content']));
        $newInfo['desc'] = mb_substr($newInfo['desc'], 0, 70);

        unset($newInfo['images']);
        unset($newInfo['in_redis']);

        if($newInfo['view'] == 0){
            $newInfo['view'] = rand(10030,15000);
        }

        //设置新闻有序集合 根据ID时间倒序
        Yii::$app->redis->ZAdd('newsZset',$newInfo['create_time'],$id);

        //设置热门新闻有序集合
        Yii::$app->redis->ZAdd('newsViewZset',$newInfo['view'],$id);

        //设置新闻Hash
        RedisService::setHash('news:'.$id,$newInfo);


        return true;
    }

    /**
     * @desc 获取浏览量最大的文章倒叙
     * @param int $currentPage
     * @param int $perPage
     * @param array $fields
     * @return mixed
     */
    public static function getMaxViewNews($currentPage = 1, $perPage = 10,$fields = []){
        $rs = RedisService::pageData('newsViewZset',$currentPage,$perPage,'zset');

        $rs['data'] = static::formatNews($rs['data'],$fields);

        return $rs;
    }


    public static function randNews($limit = 10,$fields = []){
        $newsIds = Yii::$app->get('redis')->zrevrange('newsZset',1,100);
        $newsIndex = array_rand($newsIds,$limit);

        $rs = [];
        foreach($newsIndex as $index){
            $tmp = static::getNewsInfoById($newsIds[$index],$fields);
            !empty($tmp) && $rs[] = $tmp;
        }

        return $rs;
    }


}
